import { Body, Controller, Get, Param, Post, Req } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { Request } from 'express';
import { ACCOUNT_ID } from '../../common/constants/auth.constant';
import { Public } from '../../common/decorators/public.decorator';
import { DemoService } from './demo.service';
import { Demo } from './entities/demo.entity';
import { DemoVo, DemoVoList } from './vo/demo.vo';
import { BatchCreateDemoDto } from './dto/create-demo.dto';

@Controller('demo')
export class DemoController {
  constructor(private readonly demoService: DemoService) {}

  @Post('create')
  async create(@Body() body: { name: string }, @Req() request: Request) {
    return await this.demoService.createDemo({
      owner: request[ACCOUNT_ID],
      ...body,
    });
  }

  @Post('update')
  async update(@Body() body: { id: string; name: string }) {
    return await this.demoService.updateDemo(body.id, { name: body.name });
  }

  @Post('save')
  async save(
    @Body() body: { id?: string; name: string },
    @Req() request: Request,
  ) {
    return await this.demoService.saveDemo({
      owner: request[ACCOUNT_ID],
      ...body,
    });
  }

  @Post('remove')
  async remove(@Body() body: { id: string }) {
    return await this.demoService.removeDemo(body.id);
  }

  @Public()
  @Post('find-page')
  async findPage(@Body() body: any): Promise<{ rows: Demo[]; total: number }> {
    const { rows, total } = await this.demoService.findRowsAndTotal(body);
    return {
      rows,
      total,
    };
  }

  @Public()
  @Post('find-demo-vo-list')
  async findDemoVos(@Body() body: any): Promise<DemoVoList> {
    const { rows, total } = await this.demoService.findDemoVos(body);
    return {
      rows: plainToInstance(DemoVo, rows),
      total,
    };
  }

  @Post('test')
  async test(
    @Body() body: { categoryName: string; demoName: string },
    @Req() request: Request,
  ) {
    return await this.demoService.testTransaction(
      body.categoryName,
      body.demoName,
      request[ACCOUNT_ID],
    );
  }

  @Public()
  @Post('find-tabel-rows')
  async findTabelRows(@Body() body: { tabel: string }) {
    return await this.demoService.findTableRows(body.tabel);
  }

  @Post('batch-add')
  async batchAdd(@Body() body: BatchCreateDemoDto[], @Req() request: Request) {
    return await this.demoService.batchAdd(body, request[ACCOUNT_ID]);
  }

  @Public()
  @Get(':name?')
  async findOne(@Param('name') name?: string) {
    console.log('find demo name:', name);

    return await this.demoService.find(name);
  }
}
